﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using FreeSql.Internal.Model;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Core.Extension;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;

namespace Bzzb.Controllers
{
    public class BaoZhangSheBeiController : BaseController
    {
        private readonly IWebHostEnvironment _env;
        private readonly IConfiguration _configuration;
        private readonly ILogger<BaoZhangSheBeiController> _logger;
        public BaoZhangSheBeiController(ILogger<BaoZhangSheBeiController> logger, IFreeSql fsql, IConfiguration configuration, IWebHostEnvironment env) : base(fsql)
        {
            this._env = env;
            this._logger = logger;
            this._configuration = configuration;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] string content, [FromForm] long bstid = 1, [FromForm] int doPage = 1, [FromForm] int pageNumber = 1, [FromForm] int pageSize = 10)
        {
            DynamicFilterInfo dyfilter = JsonConvert.DeserializeObject<DynamicFilterInfo>(@"
{
  'Logic' : 'Or',
  'Filters' :
  [
    {
      'Field' : 'Sbmc',
      'Operator' : 'Contains',
      'Value' : '" + content + @"',
    },{
      'Field' : 'Bzsbwybm',
      'Operator' : 'Contains',
      'Value' : '" + content + @"',
    }
  ]
}
");
            List<BaoZhangSheBei> baozhangshebeis;
            long total = 0;
            if (doPage == 0) {
                baozhangshebeis = await _fsql.Select<BaoZhangSheBei>().Where(bzsb => bzsb.Bstid == bstid).WhereDynamicFilter(dyfilter).ToListAsync();
            }else {
                baozhangshebeis = await _fsql.Select<BaoZhangSheBei>().Where(bzsb => bzsb.Bstid == bstid).WhereDynamicFilter(dyfilter).Count(out total).Page(pageNumber, pageSize).ToListAsync();
            }
            JArray ja_baozhangshebeis = new();
            foreach (var baozhangshebei in baozhangshebeis)
            {
                JObject jo_baozhangshebei = JObject.FromObject(baozhangshebei);
                BaoZhangZhuangBeiIOT baozhangzhuangbeiiot = await _fsql.Select<BaoZhangZhuangBeiIOT>().Where(bzzbiot => bzzbiot.Bzzbtid == 2 && bzzbiot.Bzzbid == baozhangshebei.Bstid && bzzbiot.Jtid == baozhangshebei.Id && bzzbiot.Gjid == 0).OrderByDescending(bzzbiot => bzzbiot.Id).Limit(1).ToOneAsync();
                jo_baozhangshebei.Add("dpzt", baozhangzhuangbeiiot?.Dpzt);
                jo_baozhangshebei.Add("fdjzt", baozhangzhuangbeiiot?.Fdjzt);
                jo_baozhangshebei.Add("xdcdy", baozhangzhuangbeiiot?.Xdcdy);
                jo_baozhangshebei.Add("yxyl", baozhangzhuangbeiiot?.Yxyl);
                jo_baozhangshebei.Add("yh", baozhangzhuangbeiiot?.Yh);
                jo_baozhangshebei.Add("ltqy", baozhangzhuangbeiiot?.Ltqy);
                jo_baozhangshebei.Add("sxwd", baozhangzhuangbeiiot?.Sxwd);
                jo_baozhangshebei.Add("hy", baozhangzhuangbeiiot?.Hy);
                jo_baozhangshebei.Add("xssd", baozhangzhuangbeiiot?.Xssd);
                jo_baozhangshebei.Add("sczt", baozhangzhuangbeiiot?.Sczt);
                jo_baozhangshebei.Add("zxwz", baozhangzhuangbeiiot?.Zxwz);
                jo_baozhangshebei.Add("ygyl", baozhangzhuangbeiiot?.Ygyl);
                jo_baozhangshebei.Add("mqzt", baozhangzhuangbeiiot?.Mqzt);
                //jo_baozhangshebei.Add("position", baozhangzhuangbeiiot == null ? null : JObject.FromObject(baozhangzhuangbeiiot));
                ja_baozhangshebeis.Add(jo_baozhangshebei);
            }
            JObject data = new();
            data.Add("total", total);
            data.Add("list", ja_baozhangshebeis);
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] BaoZhangSheBei baozhangshebei)
        {
            long id = await _fsql.Insert(baozhangshebei).ExecuteIdentityAsync();
            baozhangshebei.Id = id;

            await _fsql.Update<BaoZhangSheBei>(id).Set(bzsb => bzsb.Bzsbwybm, baozhangshebei.Bzsbwybm + String.Format("{0:D6}", id)).ExecuteAffrowsAsync();

            return RenderJson(data: baozhangshebei);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            BaoZhangSheBei baozhangshebei = await _fsql.Select<BaoZhangSheBei>().Where(bzsb => bzsb.Id == id).ToOneAsync();
            int affrows = await _fsql.Delete<BaoZhangSheBei>().Where(bzsb => bzsb.Id == id).ExecuteAffrowsAsync();
            // 删除加油车定期控制项和构件 // 1.保障车辆 2.保障设备 3.保障构件车辆 4.保障构件设备  1)电源车 2）加油车
            await _fsql.Delete<DingQiKongZhiXiang>().Where(dqkzx => dqkzx.Bzzbtid == 2 && dqkzx.Bzzbid == baozhangshebei.Bstid && dqkzx.Jtid == id).ExecuteAffrowsAsync();
            await _fsql.Delete<GouJianZhuangBei>().Where(gjzb => gjzb.Bzzbtid == 2 && gjzb.Bzzbid == baozhangshebei.Bstid && gjzb.Jtid == id).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] BaoZhangSheBei baozhangshebei) {
            int affrows = await _fsql.Update<BaoZhangSheBei>().SetSourceIgnore(baozhangshebei, colval => colval == null).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            BaoZhangSheBei baozhangshebei = await _fsql.Select<BaoZhangSheBei>().Where(bzsb => bzsb.Id == id).ToOneAsync();
            return RenderJson(data: baozhangshebei);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> DownloadExcelTemplate([FromForm] long bstid)
        {
            BaoZhangSheBeiType baozhangshebeitype = await _fsql.Select<BaoZhangSheBeiType>().Where(bzsbt => bzsbt.Id == bstid).ToOneAsync();
            JObject jo_fieldinfo = JObject.Parse(baozhangshebeitype.Fieldinfo);
            IExcelExporter exporter = new ExcelExporter();
            var filePath = @"wwwroot/download/bzsb/保障设备模板.xlsx";
            var arr = new[] { "战区", "军区", "师区", "团区", "标准总序号", "机型", "类型", "内外场", "专业", jo_fieldinfo.GetValue("bzsbwybm").ToString() + "(前缀)", jo_fieldinfo.GetValue("sbmc").ToString(), jo_fieldinfo.GetValue("xh").ToString(), jo_fieldinfo.GetValue("cfkq").ToString(), jo_fieldinfo.GetValue("sysj").ToString(), jo_fieldinfo.GetValue("gnyt").ToString(), jo_fieldinfo.GetValue("sccj").ToString(), jo_fieldinfo.GetValue("cchm").ToString(), jo_fieldinfo.GetValue("ccrq").ToString(), jo_fieldinfo.GetValue("bgsywhr").ToString(), "库区具体位置", /*"设备图像", */"接装日期", "接装验收人", "调配类型", "调配日期", "调配依据", "调配说明", "外形尺寸", "体积", "寿命", "是否质保期内", "质保期", "质保期起算日期" };
            var sheetName = "保障设备";
            var result = await exporter.ExportHeaderAsByteArray(arr, sheetName);
            result.ToExcelExportFileInfo(filePath);
            JObject data = new();
            data.Add("url", _configuration.GetValue<string>("UploadUrl") + $"/download/bzsb/保障设备模板.xlsx");
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> ExportExcel([FromForm] long bstid)
        {
            IExporter exporter = new ExcelExporter();
            var result = await exporter.Export(@"wwwroot/download/bzsb/保障设备.xlsx", await _fsql.Select<BaoZhangSheBei>().Where(bzsb => bzsb.Bstid == bstid).ToListAsync());

            JObject data = new();
            data.Add("url", _configuration.GetValue<string>("UploadUrl") + $"/download/bzsb/保障设备.xlsx");
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> ImportExcel([FromForm] long bstid, [FromForm] string filePath)
        {
            //filePath = @"upload/excel/保障设备模板.xlsx";
            string webrootpath = _env.WebRootPath;
            FileInfo file = new FileInfo(Path.Combine(webrootpath, filePath));

            long affrows = 0;
            _fsql.Transaction(() => {
                try
                {
                    using (ExcelPackage package = new ExcelPackage(file))
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets.First();
                        int rowCount = worksheet.Dimension.Rows;
                        for (int row = 2; row <= rowCount; row++)
                        {
                            //BaoZhangSheBei baozhangshebei = new BaoZhangSheBei { Bstid = bstid, Zq = worksheet.Cells[row, 1].Value?.ToString() ?? "", Jq = worksheet.Cells[row, 2].Value?.ToString() ?? "", Sq = worksheet.Cells[row, 3].Value?.ToString() ?? "", Tq = worksheet.Cells[row, 4].Value?.ToString() ?? "", Bzzxh = worksheet.Cells[row, 5].Value?.ToString() ?? "", Jx = worksheet.Cells[row, 6].Value?.ToString() ?? "", Lx = worksheet.Cells[row, 7].Value?.ToString() ?? "", Nwc = worksheet.Cells[row, 8].Value?.ToString() ?? "", Zy = worksheet.Cells[row, 9].Value?.ToString() ?? "", Bzsbwybm = worksheet.Cells[row, 10].Value?.ToString() ?? "", Sbmc = worksheet.Cells[row, 11].Value?.ToString() ?? "", Xh = worksheet.Cells[row, 12].Value?.ToString() ?? "", Cfkq = worksheet.Cells[row, 13].Value?.ToString() ?? "", Sysj = worksheet.Cells[row, 14].Value?.ToString() ?? "", Gnyt = worksheet.Cells[row, 15].Value?.ToString() ?? "", Sccj = worksheet.Cells[row, 16].Value?.ToString() ?? "", Cchm = worksheet.Cells[row, 17].Value?.ToString() ?? "", Ccrq = worksheet.Cells[row, 18].GetValue<DateTime>(), Bgsywhr = worksheet.Cells[row, 19].Value?.ToString() ?? "", Kqjtwz = worksheet.Cells[row, 20].Value?.ToString() ?? "", Sbtx = worksheet.Cells[row, 21].Value?.ToString() ?? "", Jzrq = worksheet.Cells[row, 22].GetValue<DateTime>(), Jzysr = worksheet.Cells[row, 23].Value?.ToString() ?? "", Dplx = worksheet.Cells[row, 24].Value?.ToString() ?? "", Dprq = worksheet.Cells[row, 25].GetValue<DateTime>(), Dpyj = worksheet.Cells[row, 26].Value?.ToString() ?? "", Dpsm = worksheet.Cells[row, 27].Value?.ToString() ?? "", Wxcc = worksheet.Cells[row, 28].Value?.ToString() ?? "", Tj = worksheet.Cells[row, 29].Value?.ToString() ?? "", Sm = worksheet.Cells[row, 30].Value?.ToString() ?? "", Sfzbqn = worksheet.Cells[row, 31].Value?.ToString() ?? "", Zbq = worksheet.Cells[row, 32].Value?.ToString() ?? "", Zbqqsrq = worksheet.Cells[row, 33].GetValue<DateTime>() };
                            BaoZhangSheBei baozhangshebei = new BaoZhangSheBei { Bstid = bstid, Zq = worksheet.Cells[row, 1].Value?.ToString() ?? "", Jq = worksheet.Cells[row, 2].Value?.ToString() ?? "", Sq = worksheet.Cells[row, 3].Value?.ToString() ?? "", Tq = worksheet.Cells[row, 4].Value?.ToString() ?? "", Bzzxh = worksheet.Cells[row, 5].Value?.ToString() ?? "", Jx = worksheet.Cells[row, 6].Value?.ToString() ?? "", Lx = worksheet.Cells[row, 7].Value?.ToString() ?? "", Nwc = worksheet.Cells[row, 8].Value?.ToString() ?? "", Zy = worksheet.Cells[row, 9].Value?.ToString() ?? "", Bzsbwybm = worksheet.Cells[row, 10].Value?.ToString() ?? "", Sbmc = worksheet.Cells[row, 11].Value?.ToString() ?? "", Xh = worksheet.Cells[row, 12].Value?.ToString() ?? "", Cfkq = worksheet.Cells[row, 13].Value?.ToString() ?? "", Sysj = worksheet.Cells[row, 14].Value?.ToString() ?? "", Gnyt = worksheet.Cells[row, 15].Value?.ToString() ?? "", Sccj = worksheet.Cells[row, 16].Value?.ToString() ?? "", Cchm = worksheet.Cells[row, 17].Value?.ToString() ?? "", Ccrq = worksheet.Cells[row, 18].GetValue<DateTime>(), Bgsywhr = worksheet.Cells[row, 19].Value?.ToString() ?? "", Kqjtwz = worksheet.Cells[row, 20].Value?.ToString() ?? "", /*Sbtx = worksheet.Cells[row, 21].Value?.ToString() ?? "", */Jzrq = worksheet.Cells[row, 21].GetValue<DateTime>(), Jzysr = worksheet.Cells[row, 22].Value?.ToString() ?? "", Dplx = worksheet.Cells[row, 23].Value?.ToString() ?? "", Dprq = worksheet.Cells[row, 24].GetValue<DateTime>(), Dpyj = worksheet.Cells[row, 25].Value?.ToString() ?? "", Dpsm = worksheet.Cells[row, 26].Value?.ToString() ?? "", Wxcc = worksheet.Cells[row, 27].Value?.ToString() ?? "", Tj = worksheet.Cells[row, 28].Value?.ToString() ?? "", Sm = worksheet.Cells[row, 29].Value?.ToString() ?? "", Sfzbqn = worksheet.Cells[row, 30].Value?.ToString() ?? "", Zbq = worksheet.Cells[row, 31].Value?.ToString() ?? "", Zbqqsrq = worksheet.Cells[row, 32].GetValue<DateTime>() };
                            long id = _fsql.Insert(baozhangshebei).ExecuteIdentity();
                            _fsql.Update<BaoZhangSheBei>(id).Set(bzsb => bzsb.Bzsbwybm, baozhangshebei.Bzsbwybm + String.Format("{0:D6}", id)).ExecuteAffrows();
                            affrows = row;
                        }
                    }
                }
                catch (Exception e)
                {
                    affrows = -1;
                    _logger.LogInformation("导入保障设备失败：" + e.Message);
                }

            });
            if (affrows == -1)
            {
                return RenderJson(status: "failed", message: "导入保障设备失败", code: -1);
            }
            return RenderJson(data: affrows);
        }
    }
}
